<template>
  <div class="sandwich-generator" :class="currentTheme">
    <!-- 应用介绍 -->
    <div class="app-intro">
      <h1>创意三明治生成器</h1>
      <p>解决"冰箱剩菜怎么吃"的日常痛点！</p>
      <p>只需输入手边食材（如鸡蛋、番茄、芝士），将为您生成创意三明治食谱</p>
      <p>让剩菜变身美味料理，减少食物浪费</p>
    </div>
    <!-- 用户输入模块 -->
    <div class="icons">
        <span class="theme-icon" @click="showThemeDialog = true">🎨</span>
        <span class="theme-icon" @click="selectTheme('theme-food')">🍔</span>
        <span class="theme-icon" @click="selectTheme('theme-fresh')">🍃</span>
        <span class="theme-icon" @click="selectTheme('theme-warm')">☀️</span>
      </div>
      <div class="input-section">
      <div class="input-container">
        <input 
          ref="inputField"
          v-model="ingredients"
          @input="handleInput"
          placeholder="请输入食材，用逗号分隔"
          maxlength="100"
          class="ingredient-input"
        />
        <span class="char-counter">{{ ingredients.length }}/100</span>
        <button 
          v-if="ingredients" 
          @click="clearInput"
          class="clear-btn"
        >
          ×
        </button>
      </div>
      <div class="button-group">
        <button 
          @click="generateRecipe" 
          :disabled="!ingredients"
          class="generate-btn"
        >
          生成食谱
        </button>
        <button 
          @click="useExample" 
          class="example-btn"
        >
          使用示例
        </button>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="loading" class="overlay">
      <div class="loading-spinner">正在生成食谱...</div>
    </div>

    <!-- 结果展示 -->
    <div v-if="recipe" class="result-section">
      <h2>{{ recipe.name }}</h2>
      
      <div class="ingredients-list">
        <h3>所需食材:</h3>
        <ul>
          <li v-for="(item, index) in recipe.ingredients" :key="index">
            {{ item }}
          </li>
        </ul>
      </div>
      
      <div class="steps">
        <h3>制作步骤:</h3>
          <span v-for="(step, index) in recipe.steps" :key="index" >
            <div v-html="build(step)"></div>
          </span>
      </div>
      <div v-if="stepImages.length > 0" class="step-images">
        <img 
          v-for="(img, index) in stepImages" 
          :key="index" 
          :src="img" 
          :alt="'步骤' + (index + 1)"
        />
      </div>
      
      <div class="action-buttons">
        <button @click="saveToHistory" class="save-btn">保存记录</button>
        <button @click="shareRecipe" class="share-btn">分享</button>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-toast">
      {{ error }}
    </div>
    
    <!-- 分享弹窗 -->
    <div v-if="showShareDialog" class="share-dialog-overlay">
      <div class="share-dialog">
        <h3>分享食谱</h3>
        <p>当前页面链接：</p>
        <div class="share-url">
          <input type="text" readonly v-model="shareUrl" class="share-input" />
        </div>
        <div class="share-actions">
          <button @click="copyShareUrl" class="copy-btn">复制链接</button>
          <button @click="showShareDialog = false" class="close-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Marked from 'marked';
import sandwich from '@/assets/sandwich.png';
export default {
  name: 'SandwichGenerator',
  data() {
    return {
      sandwich: sandwich,
      // 当前主题，从localStorage获取或使用默认主题
      currentTheme: localStorage.getItem('sandwichTheme') || 'theme-default',
      // 主题列表配置
      themeList: [
        { name: '默认主题', value: 'theme-default' },
        { name: '美食主题', value: 'theme-food' },
        { name: '清新主题', value: 'theme-fresh' },
        { name: '温馨主题', value: 'theme-warm' }
      ],
      // 示例食材组合
      exampleIngredients: [
        '大米,饺子，青菜叶'
       
      ],
      // 当前输入的食材
      ingredients: '大米,饺子，青菜叶',
      // 加载状态标识
      loading: false,
      // 生成的食谱数据
      recipe: null,
      // 食谱步骤图片列表
      stepImages: [],
      // 错误信息
      error: null,
      // 历史记录
      history: [],
      // 分享相关
      showShareDialog: false,
      shareUrl: ''
    }
  },
  mounted() {
    this.$refs.inputField.focus();
    this.loadHistory();
  },
  methods: {
    build(step) {
      return Marked.parse(step);
    },
    selectTheme(theme) {
      this.currentTheme = theme;
      localStorage.setItem('sandwichTheme', theme);
      this.showToast('主题已切换');
    },
    handleInput() {
      if (this.ingredients.length > 100) {
        this.ingredients = this.ingredients.substring(0, 100);
      }
    },
    clearInput() {
      this.ingredients = '';
    },
    useExample() {
      const randomIndex = Math.floor(Math.random() * this.exampleIngredients.length);
      this.ingredients = this.exampleIngredients[randomIndex];

      const content = "\n\n### 饺子与青菜饭团三明治食谱  \n**特点**：将传统饺子与米饭结合，搭配清脆青菜，制作一款咸香多汁的中式风味三明治。  \n\n---\n\n#### **食材**  \n（2人份）  \n- **饺子** 10个（煮熟后切碎）  \n- **米饭** 1碗（隔夜冷饭最佳，或煮熟后晾凉）  \n- **青菜叶** 4-5片（如生菜、油麦菜或菠菜叶）  \n- **面包片** 4片（全麦或吐司面包）  \n- **酱料**：沙拉酱/千岛酱 2大勺，酱油 1小勺，芝麻油 1小勺  \n- **调味料**：盐、黑胡椒、白芝麻（可选）  \n\n---\n\n#### **步骤**  \n1. **预处理食材**  \n   - **煮饺子**：将饺子沸水煮熟（约5分钟），捞出沥干后切碎。  \n   - **炒饭调味**：将米饭与酱油、芝麻油、少许盐和黑胡椒混合拌匀（可加入少许煎香的葱花提香）。  \n   - **煎饺子碎**（可选）：在平底锅中加入少许油，将切碎的饺子煎至边缘微焦，增加香气。  \n\n2. **组装三明治**  \n   - **预热面包**：将面包片放入烤箱或平底锅中煎至两面微焦，增加酥脆口感。  \n   - **涂抹酱料**：在面包片上均匀涂抹沙拉酱或千岛酱。  \n   - **铺青菜叶**：放上洗净沥干的青菜叶（如生菜叶），增加清新口感。  \n   - **夹入馅料**：  \n     - 第一层：铺上拌好的调味米饭。  \n     - 第二层：放上煎过的饺子碎。  \n     - 可撒上黑胡椒或白芝麻增香。  \n   - **盖上面包**：将另一片面包盖上，轻轻压实。  \n\n3. **切块与享用**  \n   - 将三明治对角切开，方便食用。  \n   - 配搭蘸酱（如酱油混合少许芝麻油）享用，"
        this.recipe =  {
          name: 'AI生成三明治',
          ingredients: this.ingredients.split(',').map(i => i.trim()),
          steps: content.split('\n')
        };

        const response = JSON.parse(`{
    "images": [
        {
            "url": "${sandwich}"
        }
    ],
    "timings": {
        "inference": 0.672
    },
    "seed": 366266646,
    "shared_id": "0",
    "data": [
        {
            "img": "${process.env.BASE_URL}/assets/sandwich.png"
        }
    ],
    "created": 1747575648
}`)
        this.stepImages = response.images.map(img => img.url);
        console.log(this.stepImages);
    },
    async generateRecipe() {
      this.loading = true;
      this.error = null;
      
      try {
        // 调用API生成食谱
        const recipeResponse = await this.callRecipeAPI();
        
        if (!recipeResponse || Object.keys(recipeResponse).length === 0) {
          throw new Error('没有找到合适食谱');
        }
        
        this.recipe = recipeResponse;
        
        // 调用大模型生成最终成品图片
        try {
          const finalImage = await this.generateFinalImage();
          this.stepImages = finalImage;
        } catch (imgError) {
          console.error('成品图生成失败:', imgError);
          this.stepImages = [];
        }
        
      } catch (error) {
        this.showError(error.message || '网络连接失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    async callRecipeAPI() {
      try {
        const response = await axios.post('https://api.siliconflow.cn/v1/chat/completions', {
          model: 'Qwen/QwQ-32B',
          messages: [{
            role: 'user',
            content: `根据以下食材生成一个三明治食谱: ${this.ingredients}`
          }],
          stream: false,
          max_tokens: 512,
          temperature: 0.7
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        const content = response.data.choices[0].message.content;
        return {
          name: 'AI生成三明治',
          ingredients: this.ingredients.split(',').map(i => i.trim()),
          steps: content.split('\n')
        };
      } catch (error) {
        throw new Error('食谱生成失败: ' + error.message);
      }
    },
    async generateFinalImage() {
      try {
        const response = await axios.post('https://api.siliconflow.cn/v1/images/generations', {
          model: 'Kwai-Kolors/Kolors',
          prompt: `根据以下食谱生成三明治成品图片: ${JSON.stringify(this.recipe)}`,
          negative_prompt: '',
          image_size: '1024x1024',
          batch_size: 1,
          seed: Math.floor(Math.random() * 1000000000),
          num_inference_steps: 20,
          guidance_scale: 7.5
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        return response.data.images.map(img => img.url);        
      } catch (error) {
        console.error('图片生成失败:', error);
        return [];
      }
    },
    showError(message) {
      this.error = message;
      setTimeout(() => {
        this.error = null;
      }, 3000);
    },
    saveToHistory() {
      if (!this.recipe) return;
      
      const record = {
        date: new Date().toLocaleString(),
        ingredients: this.ingredients,
        recipeName: this.recipe.name
      };
      
      this.history.unshift(record);
      if (this.history.length > 5) {
        this.history.pop();
      }
      
      localStorage.setItem('sandwichHistory', JSON.stringify(this.history));
    },
    loadHistory() {
      const saved = localStorage.getItem('sandwichHistory');
      if (saved) {
        this.history = JSON.parse(saved);
      }
    },
    shareRecipe() {
      // 获取当前页面URL
      this.shareUrl = window.location.href;
      this.showShareDialog = true;
      
      // 如果浏览器支持原生分享API，则使用原生分享
      if (navigator.share) {
        navigator.share({
          title: this.recipe.name,
          text: '查看我用创意三明治生成器制作的食谱！',
          url: this.shareUrl
        }).catch(err => {
          console.error('分享失败:', err);
          this.showShareDialog = true;
        });
      }
    },
    copyShareUrl() {
      const input = document.createElement('input');
      input.value = this.shareUrl;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.showError('链接已复制到剪贴板');
    },
    showToast(message) {
      this.error = message;
      setTimeout(() => {
        this.error = null;
      }, 3000);
    }
  }
}
</script>

<style scoped>
/* 主题样式 */
.sandwich-generator.theme-default {
  background-color: #f9f9f9;
  color: #333;
}

.sandwich-generator.theme-food {
  background-color: #fff8f0;
  color: #5a3e36;
}

.sandwich-generator.theme-fresh {
  background-color: #f0fff4;
  color: #2d5e4a;
}

.sandwich-generator.theme-warm {
  background-color: #fff0f0;
  color: #6d3b47;
}

.app-intro {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: rgba(255,255,255,0.9);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.app-intro h1 {
  color: #4CAF50;
  margin-bottom: 15px;
}

.app-intro p {
  margin: 8px 0;
  color: #333;
  line-height: 1.6;
}

.theme-icon {
  font-size: 24px;
  cursor: pointer;
  margin: 0 5px;
  transition: transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.sandwich-generator {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Roboto', sans-serif;
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.input-container {
  position: relative;
}

.ingredient-input {
  width: 100%;
  padding: 12px 40px 12px 15px;
  border: 2px solid #4CAF50;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
  background-color: rgba(255, 255, 255, 0.8);
}

.ingredient-input:focus {
  background-color: white;
  border-color: #2E7D32;
}

.ingredient-input:focus {
  border-color: #2E7D32;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
  transform: scale(1.01);
}

.char-counter {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  color: #757575;
  font-size: 14px;
}

.clear-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 20px;
  color: #757575;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.clear-btn:hover {
  background-color: #f5f5f5;
}

.generate-btn {
  padding: 12px 24px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  min-height: 44px;
  min-width: 120px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.generate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}

.generate-btn:hover {
  background-color: #388E3C;
}

.generate-btn:disabled {
  background-color: #BDBDBD;
  cursor: not-allowed;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

.loading-spinner {
  background-color: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.result-section {
    text-align: left;
  margin-top: 30px;
  animation: fadeIn 0.5s;
}

.ingredients-list,
.steps {
  margin: 20px 0;
}

.step-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 20px 0;
}

.step-images img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
    text-align: center;
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: center;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: center;
  width: 100%;
}

.example-btn {
  padding: 12px 24px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  min-height: 44px;
  min-width: 120px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.example-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
  background-color: #1976D2;
}

.save-btn,
.share-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  min-height: 44px;
  min-width: 100px;
}

.save-btn {
  background-color: #2196F3;
  color: white;
}

.share-btn {
  background-color: #FF9800;
  color: white;
}

.error-toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #F44336;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
  animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
  z-index: 1000;
}

/* 分享弹窗样式 */
.share-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1100;
  animation: fadeIn 0.3s;
}

.share-dialog {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 500px;
}

.share-dialog h3 {
  margin-top: 0;
  color: #333;
}

.share-url {
  margin: 15px 0;
}

.share-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.share-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.copy-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.close-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

@media (max-width: 600px) {
  .theme-icon {
  font-size: 24px;
  cursor: pointer;
  margin: 0 5px;
  transition: transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.sandwich-generator {
    padding: 15px;
  }
  
  .ingredient-input {
    padding: 10px 0px 10px 0px;
  }
  
  .generate-btn {
    width: 100%;
  }
}
</style>